package com.ly.mssp.license.client.registry;

import java.io.OutputStream;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;

import com.ly.mssp.license.entity.setting.Setting;

public class Registry {
	
	private String address;
	
	private int port;
	
	private String userName;
	
	private String password;
	
	public Registry(String address, int port, String userName, String password) {
		this.address=address;
		this.port=port;
		this.userName=userName;
		this.password=password;
	}
	
	/**
	 * 
	 * 查询镜像信息
	 * 
	 * @param imageName
	 * @return
	 * @throws Exception
	 */
	public List<Image> searchImages(String imageName) throws Exception{
		RegistryClient client=new RegistryClient(this.address, this.port, this.userName, this.password);		
		return client.query(imageName);
	}

	/**
	 * 
	 * 查询镜像标签信息
	 * 
	 * @param imageName
	 * @return
	 * @throws Exception
	 */
	public List<ImageTag> searchTags(String imageName, String tagName) throws Exception{
		RegistryClient client=new RegistryClient(this.address, this.port, this.userName, this.password);		
		return client.queryTags(imageName, tagName);
	}
	

	/**
	 * 
	 * 删除镜像
	 * 
	 * @param imageName
	 * @param tagName
	 * @return
	 */
	public boolean delete(String imageName, String tagName) throws Exception{
		RegistryClient client=new RegistryClient(this.address, this.port, this.userName, this.password);		
		return client.delete(imageName, tagName);
	}
	
	
	/**
	 * 
	 * 上传镜像
	 * 
	 * @param file
	 * @return
	 */
	public boolean upload(MultipartFile file) {
		RegistryClient client=new RegistryClient(this.address, this.port, this.userName, this.password);		
		
		ImageClient tar=new ImageClient(file);
		try {
			tar.parse();
			return client.upload(tar);
		}finally {
			tar.close();
		}		
	}
	
	/**
	 * 
	 * 下载镜像信息
	 * 
	 * @param imageName
	 * @param tagName
	 * @return
	 */
	public boolean download(String imageName, String tagName, OutputStream out) throws Exception{
				
		RegistryClient client=new RegistryClient(this.address, this.port, this.userName, this.password);	
		
		String name=imageName+"-"+tagName;
		name=name.replace("/", "-");
		
		ArchiveClient tar=new ArchiveClient(out, name);
		try {
			client.download(imageName, tagName, tar);
			tar.flush();
		}finally {
			tar.close();
		}
		return true;
	}
	
	/**
	 * 
	 * 下载镜像信息
	 * 
	 * @param imageName
	 * @param tagName
	 * @return
	 */
	public boolean clone(String imageName, String tagName, RegistryClient target) throws Exception{
				
		RegistryClient client=new RegistryClient(this.address, this.port, this.userName, this.password);	
		
		return client.clone(imageName, tagName, target);
	
	}
}

